﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Globalization;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Reflection;
using System.IO;
using System.Xml.Serialization;

namespace Utility
{
    public struct ROI
    {
        public Point ptStart;
        public Point ptEnd;
        public ROI(Point ptS, Point ptE)
        {
            ptStart = new Point(ptS.X, ptS.Y);
            ptEnd = new Point(ptE.X, ptE.Y);
        }
    }


    public struct GlobalVals
    {
        static public string sCalibFile = "";
        static public int totalSample;
        static public bool hasBuffy;
        static public int curBatch;
        static public int maxSamplesPerBatch;
        static public int samplesThisBatch;
        static public void NextBatch()
        {
            curBatch++;
            GlobalVals.samplesThisBatch = 10;
            if (GlobalVals.totalSample < GlobalVals.maxSamplesPerBatch * GlobalVals.curBatch)
                GlobalVals.samplesThisBatch = GlobalVals.totalSample % GlobalVals.maxSamplesPerBatch;

        }
    }
    public struct MARKER_POS
    {
        public double high;
        public double low;
        public MARKER_POS(double h, double l)
        {
            high = h;
            low = l;
        }
    }


    public class Helper
    {
        static string sSaveFolder = "";
        static public string GetSaveFolder()
        {
            if (sSaveFolder != "")
                return sSaveFolder;

            sSaveFolder = Calib.GetExeFolder() + "Data\\";
            sSaveFolder += "\\" + DateTime.Now.ToString("yyyyMMdd");
            if (!Directory.Exists(sSaveFolder))
            {
                Directory.CreateDirectory(sSaveFolder);
            }

            sSaveFolder += "\\" + DateTime.Now.ToString("HHmmss");
            if (!Directory.Exists(sSaveFolder))
            {
                Directory.CreateDirectory(sSaveFolder);
            }
            return sSaveFolder + "\\";
        }
    }
  
    [Serializable]
    public class Calib
    {
        public static readonly double ratio = 0.8;      //高和宽都是实际长度的80%
        public static readonly double yShift = 160;     //y从pixel 160开始
        public static readonly double bottomPos = 769;  //底部的像素Y坐标位置是769
        public List<MARKER_POS> calibPositions = new List<MARKER_POS>();
        public List<ROI> roiList = new List<ROI>();
        public double highHeight;
        public double highVolume;
        public double lowHeight;
        public double lowVolume;
        static Calib calib = null;

        public static Calib Instance
        {
            get
            {
                if (calib != null)
                    return calib;
                calib = new Calib();

                string sFile = GlobalVals.sCalibFile;
                if (sFile == "")
                {
                    sFile = GetCalibFolder() + "default.xml";
                }

                if (File.Exists(sFile))
                {
                    SerializeHelper.LoadSettings(ref calib, sFile);
                }
                else
                {
                    calib.SetDefaultValues();
                }
                return calib;
            }
        }
        public Calib()
        {
        }

        static public string GetCalibFolder()
        {
            string s = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            s += "\\Calib\\";
            if (!Directory.Exists(s))
                Directory.CreateDirectory(s);
            return s;
        }
        static public string GetExeFolder()
        {
            string s = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            return s + "\\";
        }


        private void SetDefaultValues()
        {
            Point ptStart = new Point(90, 400);
            Point ptEnd = new Point(115, 700);
            
            for (int i = 0; i < 10; i++)
            {
                roiList.Add(new ROI(new Point(ratio * (ptStart.X + i * 110), ratio * ptStart.Y), new Point(ratio * (ptEnd.X + i * 110), ratio * ptEnd.Y)));
                calibPositions.Add(new MARKER_POS(500 * ratio, 600 * ratio));
            }
        }

        public void Write2ROI4Cpp()
        {
            
            string s = GetCalibFolder() + "roi.txt";

            //y shift = 0.1*1600 = 160;
            using (StreamWriter sw = new StreamWriter(s))
            {
                foreach (ROI roi in roiList)
                {
                    sw.WriteLine(string.Format("{0} {1} {2} {3}", (int)(roi.ptStart.X / ratio), (int)(roi.ptStart.Y / ratio + yShift), (int)(roi.ptEnd.X / ratio), (int)(roi.ptEnd.Y / ratio + yShift)));
                }
            }
        }
    }
    public class SerializeHelper
    {

        static public void SaveSettings(Calib config, string sFile)
        {
            int pos = sFile.LastIndexOf("\\");
            string sDir = sFile.Substring(0, pos);

            if (!Directory.Exists(sDir))
                Directory.CreateDirectory(sDir);

            if (File.Exists(sFile))
                File.Delete(sFile);

            XmlSerializer xs = new XmlSerializer(typeof(Calib));
            Stream stream = new FileStream(sFile, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite);
            xs.Serialize(stream, config);
            stream.Close();
        }

        static public void LoadSettings(ref Calib config, string sFile)
        {
            if (!File.Exists(sFile))
                throw new FileNotFoundException(string.Format("位于：{0}的配置文件不存在", sFile));
            Stream stream = new FileStream(sFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            XmlSerializer xs = new XmlSerializer(typeof(Calib));
            config = xs.Deserialize(stream) as Calib;
            stream.Close();
        }
    }
}
